﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Polly.CircuitBreaker;
using Polly.Timeout;

namespace 在_C__中使用_Polly库.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrderController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger<OrderController> _logger;

        public OrderController(IHttpClientFactory httpClientFactory, ILogger<OrderController> logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        [HttpPost]
        public async Task<IActionResult> CreateOrder([FromBody] Order order)
        {
            try
            {
                // 1. 创建已配置Polly策略的HttpClient实例
                var client = _httpClientFactory.CreateClient("ExternalApi");

                // 2. 发起HTTP请求
                // Polly会自动在后台应用我们定义的重试、熔断、超时策略
                var response = await client.PostAsJsonAsync("/payment", order);

                // 3. 确保响应是成功的（2xx）
                response.EnsureSuccessStatusCode();

                // 4. 处理成功响应...
                var result = await response.Content.ReadFromJsonAsync<PaymentResult>();
                return Ok(result);
            }
            catch (HttpRequestException ex) // 捕获HTTP请求异常
            {
                _logger.LogError(ex, "调用支付API时发生HTTP请求异常。");
                return StatusCode(502, "支付服务暂时不可用，请稍后再试。"); // Bad Gateway
            }
            catch (TimeoutRejectedException ex) // 捕获Polly超时策略抛出的异常
            {
                _logger.LogError(ex, "调用支付API超时。");
                return StatusCode(504, "支付服务响应超时，请稍后再试。"); // Gateway Timeout
            }
            catch (BrokenCircuitException ex) // 捕获Polly熔断器策略抛出的异常
            {
                _logger.LogError(ex, "调用被熔断器阻断，因为支付API已多次失败。");
                return StatusCode(503, "支付服务繁忙，请稍后再试。"); // Service Unavailable
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "创建订单时发生未知错误。");
                return StatusCode(500, "内部服务器错误");
            }
        }
    }

    public class PaymentResult
    {
    }

    public class Order
    {
    }
}